<template>
  <div>
    <h3 class="title">单文件缩略图上传</h3>
    <div class="border_dot">
      <form id="formthumb">
        <input
          ref="fileRef"
          type="file"
          style="display: none"
          accept=".png,.jpg,.jpeg,.zip"
        />
      </form>
      <button class="btn select_btn btn_sel_thumb" @click="handleFile">
        选择文件
      </button>
      <button class="btn update_btn btn_up_thumb" @click="handleUpdate">
        上传
      </button>
      <div>请上传PNG/JPG/ZIP类型图片</div>
      <div class="file_item_wrap" v-if="file">
        <img style="width: 200px" :src="base64" />
      </div>
      <Progress v-if="progress > 0" :value="progress" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import Progress from "./Progress.vue";
import { readAsDataURL } from "@/utils/index";
import { updateFile } from "@/api/update";

const fileRef = ref<null | HTMLInputElement>(null);
const file = ref<null | File>(null);
const base64 = ref("");
const progress = ref(0);

async function handleUpdate() {
  if (!file.value) {
    alert("请选择文件");
    return;
  }
  const formData = new FormData();
  formData.append("file", file.value);
  const selectBtn = document.querySelector(".btn_sel_thumb");
  const updateBtn = document.querySelector(".btn_up_thumb");
  selectBtn?.setAttribute("disabled", "disabled");
  updateBtn?.setAttribute("loading", "loading");
  try {
    const res = await updateFile<FormData, { type: number; path: string }>(
      formData,
      {
        onUploadProgress: (ev: ProgressEvent) => {
          progress.value = Math.ceil((ev.loaded / ev.total) * 100);
        },
      }
    );
    res.type === 0 ? alert("文件已存在") : alert("上传成功");
    file.value = null;
    (document.querySelector("#formthumb") as HTMLFormElement).reset();
  } finally {
    progress.value = 0;
    selectBtn?.removeAttribute("disabled");
    updateBtn?.removeAttribute("loading");
  }
}
function handleFile() {
  fileRef.value?.click();
}
function handleRemove() {
  file.value = null;
}
onMounted(() => {
  fileRef.value?.addEventListener("change", async (ev: Event) => {
    file.value = (ev.target as HTMLInputElement).files![0];
    console.log(file.value);

    base64.value = await readAsDataURL<string>(file.value);
  });
});
</script>

<style></style>
